<script >

import axios from "axios";
import {attachImg} from "@/api";
import {ElMessage} from "element-plus";


export default {
  name:'ShopPage',
  data(){
      return{
        drugList:[],//药品
        formInfo:{},//携带分页数据
        options:[],//一级菜单选项
        options1:[],//二级菜单选项
        value:'',//一级选中值
        value2:'',//二级选中值
        totalCount:0,
        currentPage:1,
        pageSize:4,
        issingle:true,
        showPagination:true,
        drawer:false,
        drawer1:false,
        currentDrug:null,
        num: 1, // 默认购买数量

      }
  },
  mounted() {
        this.getAllSymptomatic()
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getAllDrugs();
    });
  },
  methods:{

    addToCartConfirm() {

      // 假设你有一个后端API来处理添加到购物车的操作
      const cartItem = {
        status:1,
        userid: localStorage.getItem('userId'), // 从localStorage获取用户ID
        drugid: this.currentDrug.drugsid, // 当前药品的ID
        drugname: this.currentDrug.drugs, // 当前药品的名称
        drugnumber: this.num, // 用户选择的数量
        drugprice: this.currentDrug.drugprice, // 药品的价格
        pictrue: this.currentDrug.picture // 药品的图片路径
      };
      // 设置请求头，确保Content-Type为application/json
      const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };
      // 使用axios发送POST请求到后端API
      axios.post('http://localhost:9099/cart/add', cartItem,config)
          .then(response => {
            ElMessage({
              message:response.data.msg,
              type:'success',
              duration:2000
            })
            // 处理响应，例如显示成功消息
            console.log('Added to cart:', response.data);
          })
          .catch(error => {
            // 处理错误，例如显示错误消息
            console.error('Error adding to cart:', error);
          });

      // 关闭抽屉
      this.drawer1 = false;
    },

    attachImg,
    getAllDrugs() {
      this.formInfo.currentPageNo=this.currentPage;
      this.formInfo.pageSize=this.pageSize;

      // 发送 GET 请求
      axios.get('http://localhost:9099/store/query',{
        params: this.formInfo,
      })
          .then(res => {
            this.drugList = res.data.data;
          })
          .catch(error => {
            console.error('请求失败:', error);
            // 处理错误，例如显示错误消息
          })
      this.getAllDrugsCount()
    },
    getAllDrugsCount() {
      // 发送 GET 请求
      axios.get('http://localhost:9099/store/querycount')
          .then(res => {
            this.totalCount = res.data.data;
          })
          .catch(error => {
            console.error('请求失败:', error);
            // 处理错误，例如显示错误消息
          });
    },
    getAllSymptomatic(){
      axios.get("http://localhost:9099/store/query2")
          .then(res=>{
            this.options=res.data.data;
          })
          .catch(error =>{
            console.error('请求失败',error)
          })
    },
    updateSubcategoryOptions() {
      // 根据选中的一级分类 ID 更新二级分类的选项列表
      if (this.value) {
        this.getAllSymptom(this.value);
      } else {
        this.options1 = [];
      }
      this.drugList=''
      this.value2=''
    },
    getAllSymptom(symptomaticid) {
      axios.get(`http://localhost:9099/store/query3?id=${symptomaticid}`)
          .then(res => {
            this.options1 = res.data.data;
          })
          .catch(error => {
            console.error('请求失败', error);
          });
    },
    onSubmit(){
      this.showPagination=false
      axios.get(`http://localhost:9099/store/query1?id=${this.value2}`)
          .then(res => {
            this.drugList = res.data.data;
          })
          .catch(error => {
            console.error('请求失败:', error);
            // 处理错误，例如显示错误消息
          });
    },
    onSubmit1(){
      this.showPagination=true
      this.getAllDrugs()
      this.value=''
      this.value2=''
    },
    oncar(){
      this.$router.push('/HomePage/shopcar')
    },
    showDetails(drug) {
      this.currentDrug = drug; // 设置当前点击的药品对象
      this.drawer = true; // 显示抽屉
    },
    addShopcar(drug) {
      this.currentDrug = drug; // 设置当前点击的药品对象
      this.drawer1 = true; // 显示抽屉
    },
  },

}
</script>

<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3"> 全部分类 </span>
    </template>
  </el-page-header>

      <el-row class="el-row">
        <el-col :span="6">
          <el-form-item label="一级分类:">
            <el-select v-model="value" placeholder="Select" style="width: 240px" @change="updateSubcategoryOptions">
              <el-option
                  v-for="item in options"
                  :key="item.symptomaticid"
                  :label="item.symptomatic"
                  :value="item.symptomaticid"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6" class="col">
          <el-form-item label="二级分类:">
            <el-select v-model="value2" placeholder="Select" style="width: 240px" @change="onSubmit">
              <el-option
                  v-for="item in options1"
                  :key="item.drugsid"
                  :label="item.drugdescription"
                  :value="item.drugsid"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-button type="primary"  @click="onSubmit1">全部药品</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="danger"  @click="oncar">购物车</el-button>
        </el-col>
      </el-row>


    <el-table :data="drugList" style="width: 100%" >
      <el-table-column fixed prop="drugs" label="药品名称" width="150" />
      <el-table-column prop="picture" label="药品图片" width="120">
        <template #default="scope">
          <el-image :src="attachImg(scope.row.picture)" width="150px"/>
        </template>
      </el-table-column>
      <el-table-column prop="drugprice" label="药品价格" width="120" />
      <el-table-column prop="drugdescription" label="症状类型" width="120" />
      <el-table-column prop="brand" label="药物品牌" width="120" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="default" @click="showDetails(scope.row)">
            详情
          </el-button>
          <el-button type="danger" size="default" @click="addShopcar(scope.row)">
            购买
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  <el-pagination background layout="prev, pager, next" :total="totalCount" default-page-size="3" v-model:current-page="currentPage" v-model:page-size="pageSize"
    @update:page-size="getAllDrugs" @update:current-page="getAllDrugs" :hide-on-single-page="issingle" v-show="showPagination"
  />

  <el-drawer
      v-model="drawer"
      title="药品详情"
      size="30%"
      :with-header="false"
  >
    <div class="drug-details">
      <div class="drug-info" v-if="currentDrug">
        <h2>{{ currentDrug.drugs }}</h2>
        <p><strong>价格:</strong> {{ currentDrug.drugprice }}</p>
        <p><strong>规格:</strong> {{ currentDrug.consumption }}</p>
        <p><strong>适应症:</strong> {{ currentDrug.indication }}</p>
        <p><strong>症状类型:</strong> {{ currentDrug.drugdescription }}</p>
        <p><strong>用法用量:</strong> {{ currentDrug.metering }}</p>
        <p><strong>主要成分:</strong> {{ currentDrug.component }}</p>
        <p><strong>用药禁忌:</strong> {{ currentDrug.taboo }}</p>
        <p><strong>不良反应:</strong> {{ currentDrug.reaction }}</p>
        <p><strong>药物相互作用:</strong> {{ currentDrug.effect }}</p>
        <p><strong>注意事项:</strong> {{ currentDrug.matter }}</p>
        <p><strong>药理毒性:</strong> {{ currentDrug.toxicity }}</p>
        <p><strong>药物品牌:</strong> {{ currentDrug.brand }}</p>
        <p><strong>药品类型:</strong> {{ currentDrug.type }}</p>
        <p><strong>药品计量:</strong> {{ currentDrug.dose }}</p>
        <p><strong>药物性状:</strong> {{ currentDrug.character }}</p>
        <p><strong>药物存储:</strong> {{ currentDrug.storage }}</p>
        <p><strong>药品保质期:</strong> {{ currentDrug.period }}</p>
        <p><strong>批准文号:</strong> {{ currentDrug.approval }}</p>
        <p><strong>生产厂家:</strong> {{ currentDrug.manufactor }}</p>
      </div>
    </div>
  </el-drawer>

  <el-drawer
      class="shopping-cart-drawer"
      v-model="drawer1"
      title="加入购物车"
      :with-header="false"
      size="30%"
  >
    <div v-if="currentDrug" class="drawer-content">
      <h2 class="drug-name">{{ currentDrug.drugs }}</h2>
      <p class="drug-price"><strong>单价:</strong> {{ currentDrug.drugprice }}</p>
      <el-input-number v-model="num" :min="1" :max="10" @change="handleChange" class="drug-quantity-input" />
      <el-button type="danger" size="default" @click="addToCartConfirm" class="add-to-cart-button">加入购物车</el-button>
    </div>
  </el-drawer>
</template>

<style >
.el-row{
  margin-top: 20px;
}
.col{
  margin-left: 10px;
}
.drug-details {
  padding: 20px;
  font-size: 14px;
  line-height: 1.5;
}

.drug-details h2 {
  margin-top: 0;
  color: #333;
}

.drug-info p {
  margin: 5px 0;
}

.drug-info p strong {
  color: #666;
}
/* 抽屉内容样式 */
.shopping-cart-drawer .drawer-content {
  padding: 20px;
}

.shopping-cart-drawer .drug-name {
  margin-bottom: 16px;
}

.shopping-cart-drawer .drug-price {
  margin-bottom: 16px;
}

.shopping-cart-drawer .drug-quantity-input {
  margin-bottom: 20px;
  width: 50%; /* 使输入框宽度适应抽屉宽度 */
}

.shopping-cart-drawer .add-to-cart-button {
  width: 60%; /* 使按钮宽度适应抽屉宽度 */
  margin-top: 10px;
}
</style>